package com.socio.resources;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.socio.behaviors.DAOBehavior;
import com.socio.behaviors.UserUDIDBehavior;
import com.socio.model.ClientUser;
import com.socio.model.User;

@Path("/allTime")
public class AllTimeResource {

	@Path("/leaderboard")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
	public String getLeaderboard(@QueryParam("udid") String udid) {
	
		// set up behaviors
        DAOBehavior userDAO = new UserUDIDBehavior();
		
        // get 3 users with highest quickScores
        String ordering = "quickScore desc";
        String queryRange = "0,3";
        Object result = userDAO.execute(null, null, ordering, queryRange, null, null);
        List<User> dbUsers = (List<User>)result;
        if(dbUsers.isEmpty() || dbUsers.get(0) == null)
        	return "";
        
        // check to see if days contain user with udid (if specified)
        List<ClientUser> resultingUsers = new ArrayList<ClientUser>();
        boolean containsRequester = false;
        if(udid == null || udid.isEmpty())
        	containsRequester = true;
        for(User user : dbUsers) {
        	ClientUser resultingUser = user.getClientUser();
        	resultingUser.setQuickScore(user.getQuickScore());
        	if(!containsRequester && user.getAndroidUDID().equalsIgnoreCase(udid)) {
        		resultingUser.setUdid(udid);
        		if(!user.getFacebookID().isEmpty())
        			resultingUser.setScoring(true);
        		containsRequester = true;
        	}
        	
        	resultingUsers.add(resultingUser);
        }
        
        // if user not part of top 3 get them and add them as a fourth
        User user = null;
        if(!containsRequester) {
        	ClientUser requestingUser = new ClientUser();
        	result = userDAO.read(udid, null);
            List<User> dbUser = (List<User>)result;
            if(!dbUser.isEmpty() && dbUser.get(0) != null) {
            	user = (User)dbUser.get(0);
            	requestingUser = user.getClientUser();
            	requestingUser.setUdid(user.getAndroidUDID());
            	requestingUser.setQuickScore(user.getQuickScore());
            	
            }
            // check to see if user is somehow earning points
        	if(user != null && !user.getFacebookID().isEmpty())
        		requestingUser.setScoring(true);
            requestingUser.setUdid(udid);
            resultingUsers.add(requestingUser);
        }
		
        Gson gson = new Gson();
		return gson.toJson(resultingUsers);
	}
}
